package de.hijacksoft.isle;

import static de.hijacksoft.isle.classes.Variables.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import de.hijacksoft.isle.adapters.DBAdapter;
import de.hijacksoft.isle.classes.Item;
import de.hijacksoft.isle.adapters.MainListAdapter;
import de.hijacksoft.isle.classes.Price;
import de.hijacksoft.isle.classes.Recipe;

public class RecipeActivity extends Activity {

    // Constants
    private static final String TAG = "RecipeActivity";
    // Variables
    private MainListAdapter myAdapter;
    private Recipe recipe;
    private DBAdapter adapter;
    private boolean editMode = false;// whether to edit a recipe or to create a new one
    private int editedRecipeId;
    // Views
    private Button add, finish;
    private EditText name;
    private RatingBar rating;
    private ListView list;
    private TextView price;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
        setContentView(R.layout.recipeactivity);
        recipe = new Recipe();

        createUI();
        initDB();
        initList();

        // try fetching recipe from db
        // if theres no recipeid in the intent jump to catch-block
        try {
            int recipeid = getIntent().getExtras().getInt(KEY_ID);
            recipe = adapter.getRecipeById(recipeid);
            name.setText(recipe.name);
            finish.setText(getString(R.string.apply));
            editMode = true;
            editedRecipeId = recipe.id;
            rating.setRating((float) (recipe.rating));
            initList();
        } catch (Exception e) {
            Log.i(TAG, "couldnt fetch recipe from db");
        }

    }

    private void initDB() {
        adapter = new DBAdapter(this);
        adapter.open();
    }

    private void createUI() {

        add = (Button) findViewById(R.id.recipeactivity_btn_add);
        finish = (Button) findViewById(R.id.recipeactivity_btn_finish);
        list = (ListView) findViewById(R.id.recipeactivity_list_ingredients);
        name = (EditText) findViewById(R.id.recipeactivity_edittext_name);
        rating = (RatingBar) findViewById(R.id.recipeactivity_ratingbar_rating);
        price = (TextView) findViewById(R.id.recipeactivity_textview_price);

        add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(RecipeActivity.this, ItemSelectActivity.class);
                i.putExtra(KEY_MODE, MODE_RECIPE);
                startActivityForResult(i, ITEM_RETURNED);// add an item
            }
        });

        finish.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                recipe.name = name.getText().toString();
                recipe.rating = rating.getRating();
                if (editMode) {
                    recipe.id = editedRecipeId;
                    adapter.updateRecipe(recipe);
                } else {
                    adapter.addRecipe(recipe);
                }
                RecipeActivity.this.setResult(RESULT_OK, null);
                RecipeActivity.this.finish();
            }
        });

        list.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                ItemEditQuestion(arg2);
                return false;
            }
        });
    }

    private void updatePrice() {
        double totalPrice = 0;
        for (int i = 0; i < recipe.ingredients.size(); i++) {
            totalPrice += recipe.ingredients.get(i).price;
        }
        price.setText(getString(R.string.price) + ": " + new Price(getApplicationContext(), totalPrice).toString());
    }

    private void initList() {
        myAdapter = new MainListAdapter(this, R.layout.item, recipe.ingredients, adapter) {

            @Override
            public void notifyDataSetChanged() {
                super.notifyDataSetChanged();
                updatePrice();
            }
        };
        myAdapter.setMode(MainListAdapter.CHECKBOX, false);
        myAdapter.setMode(MainListAdapter.PRICE, true);
        myAdapter.setMode(MainListAdapter.ICONS, true);
        myAdapter.setMode(MainListAdapter.LASTBOUGHT, false);
        myAdapter.setMode(MainListAdapter.AMOUNT, true);
        list.setAdapter(myAdapter);
        updatePrice();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ITEM_RETURNED:
                    for (int i = 0; i < data.getExtras().size(); i++) {
                        Item item = adapter.getItemById(data.getExtras().getInt("id_" + i));
                        recipe.addItem(item);
                    }
                    break;
            }
        }

        myAdapter.notifyDataSetChanged();

    }

    /**
     * Asks whether to edit or to delete an item from the recipe ingredients list
     * @param position the position in the ArrayList of items
     */
    private void ItemEditQuestion(final int position) {
        AlertDialog.Builder dB = new AlertDialog.Builder(this);
        dB.setTitle(recipe.ingredients.get(position).name);
        dB.setMessage(getString(R.string.editquestion));
        //EDIT button to edit item amount
        dB.setPositiveButton(getString(R.string.edit), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {

                AlertDialog.Builder alert = new AlertDialog.Builder(RecipeActivity.this);

                alert.setTitle(recipe.ingredients.get(position).name);
                alert.setMessage(getString(R.string.amount));

                // Set an EditText view to get user input
                final EditText input = new EditText(RecipeActivity.this);
                input.setKeyListener(DigitsKeyListener.getInstance(false, true));
                alert.setView(input);
                input.setText("" + recipe.ingredients.get(position).amount);
                alert.setPositiveButton(getString(R.string.apply),
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {
                                String amount = input.getText().toString();
                                recipe.ingredients.get(position).price *= Double.parseDouble(amount) / recipe.ingredients.get(position).amount;
                                recipe.ingredients.get(position).amount = Double.parseDouble(amount);
                                adapter.updateMainItem(recipe.ingredients.get(position));
                                myAdapter.notifyDataSetChanged();
                            }
                        });

                alert.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        // do nothing
                    }
                });
                alert.show();
            }
        });
        dB.setNegativeButton(getString(R.string.delete), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                adapter.removeFromMainList(recipe.ingredients.get(position).id);
                recipe.ingredients.remove(position);
                myAdapter.notifyDataSetChanged();
            }
        });
        AlertDialog d = dB.create();
        d.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        startActivity(new Intent(this, Preferences.class));
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        adapter.close();
    }

    @Override
    protected void onResume() {
        super.onResume();
        myAdapter.notifyDataSetChanged();
    }
}
